<template>
    <div class="purchase-inbound-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.inboundNo" style="width: 240px; padding-right: 15px;" placeholder="请输入入库单号" />
            <el-input v-model="searchParams.orderNo" style="width: 240px;" placeholder="请输入采购订单号" />
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px;margin-left: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getPurchaseInboundList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建采购入库单</el-button>
        </div>

        <!-- 采购入库单表格 -->
        <el-table :data="purchaseInboundList" style="width: 100%" stripe :border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="入库单ID" width="180" align="center" />
            <el-table-column prop="inboundNo" label="入库单号" width="180" align="center" />
            <el-table-column prop="orderNo" label="采购订单号" width="180" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" width="180" align="center" />
            <el-table-column prop="inboundDate" label="入库日期" width="180" align="center" />
            <el-table-column prop="status" label="入库状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
                <span v-if="scope.row.status == 1" style="color: green;">已入库</span>
                <span v-if="scope.row.status == 2" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewPurchaseInboundDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
                <el-button type="danger" plain @click="handleDeletePurchaseInbound(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑采购入库单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑采购入库单' : '创建采购入库单'" width="900px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="purchaseInbound" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="inboundForm">
                <el-form-item label="入库单号" prop="inboundNo" v-if="isEdit">
                    <el-input v-model="purchaseInbound.inboundNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="采购订单号" prop="orderId">
                    <el-select v-model="purchaseInbound.orderId" placeholder="请选择采购订单" clearable @change="handleOrderChange">
                        <el-option v-for="order in purchaseOrders" :key="order.id" :label="order.orderNo" :value="order.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-select v-model="purchaseInbound.warehouseId" placeholder="请选择仓库" clearable>
                        <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="入库日期" prop="inboundDate">
                    <el-date-picker v-model="purchaseInbound.inboundDate" type="date" placeholder="请选择入库日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="入库状态" prop="status" v-if="isEdit">
                    <el-select v-model="purchaseInbound.status" placeholder="请选择入库状态">
                        <el-option label="已入库" :value="1" />
                        <el-option label="已取消" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="purchaseInbound.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 采购入库单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="采购入库单详情" width="900px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentPurchaseInbound" class="purchase-detail">
                <div class="detail-header">
                    <p><span class="label">入库单号：</span>{{ currentPurchaseInbound.inboundNo }}</p>
                    <p><span class="label">采购订单号：</span>{{ currentPurchaseInbound.orderNo }}</p>
                    <p><span class="label">仓库名称：</span>{{ currentPurchaseInbound.warehouseName }}</p>
                    <p><span class="label">入库日期：</span>{{ currentPurchaseInbound.inboundDate }}</p>
                    <p><span class="label">入库状态：</span>
                        <span v-if="currentPurchaseInbound.status == 0" style="color: gray;">草稿</span>
                        <span v-if="currentPurchaseInbound.status == 1" style="color: green;">已入库</span>
                        <span v-if="currentPurchaseInbound.status == 2" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">备注：</span>{{ currentPurchaseInbound.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>采购入库单明细</h3>
                    <el-table :data="currentPurchaseInbound.items" style="width: 100%" stripe>
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="120" align="center" />
                        <el-table-column prop="amount" label="金额" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
// 导入所有需要的API方法
import { createPurchaseInbound, getPurchaseInboundPage, getWarehouse,
         getPurchaseInboundWithDetails, updatePurchaseInbound, deletePurchaseInbound } from '@/api/purchase/purchase_inbound';
import { getPurchasePage } from '@/api/purchase/purchase_order';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 采购入库单列表数据
const purchaseInboundList = ref([]);

// 采购订单列表数据（用于选择）
const purchaseOrders = ref([]);

// 仓库列表数据（用于选择）
const warehouses = ref([]);

// 搜索参数
const searchParams = ref({
    inboundNo: '',
    orderNo: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的采购入库单
const purchaseInbound = ref({});
const currentPurchaseInbound = ref(null);

// 统一解包工具：兼容拦截器返回 data 或原始对象
function unwrap(res) {
    return (res && res.data !== undefined) ? res.data : res;
}

// 表单验证规则
const formRules = ref({
    orderId: [
        { required: true, message: '请选择采购订单', trigger: 'blur' }
    ],
    warehouseId: [
        { required: true, message: '请选择仓库', trigger: 'blur' }
    ],
    inboundDate: [
        { required: true, message: '请选择入库日期', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择入库状态', trigger: 'change' }
    ]
});

// 获取采购入库单列表
function getPurchaseInboundList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        inboundNo: searchParams.value.inboundNo,
        orderNo: searchParams.value.orderNo,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getPurchaseInboundPage(pageParams).then(res => {
        const data = unwrap(res);
        purchaseInboundList.value = data?.records || [];
        pagination.value.total = data?.total || 0;
    }).catch(error => {
        ElMessage.error('获取采购入库单列表失败');
        console.error('获取采购入库单列表失败:', error);
    });
}

// 获取采购订单列表（用于选择）
function fetchPurchaseOrders() {
    const pageParams = {
        pageNum: 1,
        pageSize: 1000, // 获取足够多的订单
        status: 1 // 只查已审核的订单
    };
    getPurchasePage(pageParams).then(res => {
        const listData = unwrap(res);
        const allOrders = listData?.records || [];
        // 获取所有已存在的入库单的orderId
        getPurchaseInboundPage({ pageNum: 1, pageSize: 10000 }).then(inboundRes => {
            const inboundData = unwrap(inboundRes);
            const inboundOrderIds = (inboundData?.records || []).map(item => item.orderId);
            // 过滤掉已存在入库单的订单
            purchaseOrders.value = allOrders.filter(order => !inboundOrderIds.includes(order.id));
        });
    }).catch(error => {
        ElMessage.error('获取采购订单列表失败');
        console.error('获取采购订单列表失败:', error);
    });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
  getWarehouse().then(res => {
    const data = unwrap(res);
    warehouses.value = Array.isArray(data) ? data : [];
    console.log('仓库数据:', data); // 添加成功日志
  }).catch(error => {
    ElMessage.error('获取仓库列表失败');
    console.error('获取仓库列表失败:', error);
    console.error('错误详情:', error.response); // 添加详细错误信息
  });
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        inboundNo: '',
        orderNo: '',
        startDate: '',
        endDate: ''
    };
    getPurchaseInboundList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getPurchaseInboundList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getPurchaseInboundList();
}

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    purchaseInbound.value = { items: [] };
    dialogVisible.value = true;
    // 重置表单
    proxy.$refs.inboundForm.resetFields();
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    purchaseInbound.value = { ...row };
    dialogVisible.value = true;
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单
    proxy.$refs.inboundForm.resetFields();
}

// 选择采购订单时自动带上明细
function handleOrderChange(orderId) {
    if (!orderId) {
        purchaseInbound.value.items = [];
        return;
    }
    // 获取采购订单详情，带明细
    import('@/api/purchase/purchase_order').then(api => {
        api.getPurchaseWithDetails(orderId).then(res => {
            const data = unwrap(res);
            purchaseInbound.value.items = data?.items || [];
        });
    });
}

// 提交表单
function submitForm() {
    proxy.$refs.inboundForm.validate((valid) => {
        if (valid) {
            // 确保数据类型正确
            const formData = { ...purchaseInbound.value };
            if (formData.orderId) {
                formData.orderId = Number(formData.orderId);
            }
            if (formData.warehouseId) {
                formData.warehouseId = Number(formData.warehouseId);
            }
            if (formData.status !== undefined) {
                formData.status = Number(formData.status);
            }
            // 自动带上明细
            formData.items = purchaseInbound.value.items || [];
            if (isEdit.value) {
                updatePurchaseInbound(formData).then(res => {
                    ElMessage.success('采购入库单更新成功');
                    handleDialogClose();
                    getPurchaseInboundList();
                }).catch(error => {
                    ElMessage.error('采购入库单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                createPurchaseInbound(formData).then(res => {
                    ElMessage.success('采购入库单创建成功');
                    handleDialogClose();
                    getPurchaseInboundList();
                }).catch(error => {
                    ElMessage.error('采购入库单创建失败: ' + (error.response?.data?.message || error.message));
                    console.error('创建失败:', error);
                    console.error('错误详情:', error.response);
                });
            }
        } else {
            ElMessage.warning('请完善采购入库单信息并确保格式正确');
            return false;
        }
    });
}

// 查看采购入库单详情
function viewPurchaseInboundDetails(id) {
    // 调用获取采购入库单详情的API
    getPurchaseInboundWithDetails(id).then(res => {
        const data = unwrap(res);
        currentPurchaseInbound.value = data || null;
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取采购入库单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentPurchaseInbound.value = null;
}

// 删除采购入库单 - 重命名函数避免冲突
function handleDeletePurchaseInbound(id) {
    ElMessageBox.confirm(
        '确定要删除该采购入库单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 调用删除采购入库单的API
        deletePurchaseInbound(id).then(res => {
            ElMessage.success('采购入库单删除成功');
            getPurchaseInboundList();
        }).catch(error => {
            ElMessage.error('采购入库单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 页面加载时获取采购入库单列表、采购订单列表和仓库列表
onMounted(() => {
    getPurchaseInboundList();
    fetchPurchaseOrders();
    fetchWarehouses();
});
</script>

<style scoped>
.purchase-inbound-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.purchase-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
